package shell.view.utils;

import java.awt.Color;
import java.awt.image.BufferedImage;
/**@author Rafael Rocha*/
public class ImageConvolution {
	public static BufferedImage getConvolution(BufferedImage image, int[][] matrix){
		BufferedImage bImage = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
		
		int mWidth = matrix.length;
		int size = mWidth * mWidth;
		int sum = 0;
		for(int i = 0; i < mWidth; i++){
			for(int j = 0; j < mWidth; j++){
				sum += matrix[i][j];
			}
		}
		
		for(int i = mWidth/2; i < image.getWidth() - mWidth/2; i++) {
			for(int j = mWidth/2; j < image.getHeight() - mWidth/2; j++) {
				int red = 0, green = 0, blue = 0;
				
				for(int k = 0; k < size; k++){
					Color c = new Color(image.getRGB(i - mWidth/2 + k%mWidth,j - mWidth/2 + k/mWidth));
					
					red += c.getRed() * matrix[k%mWidth][k/mWidth];
					green += c.getGreen() * matrix[k%mWidth][k/mWidth];
					blue += c.getBlue() * matrix[k%mWidth][k/mWidth];
				}
				if(sum == 0) {sum = 1;}
				red/= sum;
				green/= sum;
				blue /= sum;
				
				red = Math.max(0, Math.min(255, red));
				green = Math.max(0, Math.min(255, green));
				blue = Math.max(0, Math.min(255, blue));
				Color c = new Color(red, green, blue);
				bImage.setRGB(i, j, c.getRGB());
			}
		}
		return bImage;
	}
}
